package com.hexinfo.dmpro.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author JunjieM
 * @Date 2022/7/12
 */
@Slf4j
@Api(tags = "系统：扩展包接口")
@RestController
@RequestMapping("/extlib")
public class ExtlibController {

    @Value("${file.extlib}")
    private String extlib;

    @Autowired
    private ResourceLoader resourceLoader;

    @ApiOperation("获取文件名称列表")
    @GetMapping("/list")
    public ResponseEntity<Object> list() {
        List<String> list = getFileNames(extlib);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    private List<String> getFileNames(String path) {
        String url = "file:" + (path + "/*").replace("\\", "/");
        List<String> list = new ArrayList<>();
        try {
            Resource[] resources = ResourcePatternUtils
                    .getResourcePatternResolver(resourceLoader).getResources(url);
            List<File> files = Arrays.stream(resources).map(r -> {
                try {
                    return r.getFile();
                } catch (IOException e) {
                    log.warn(e.getMessage(), e);
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            files.forEach(f -> {
                if (f.isFile()) {
                    list.add(f.getName());
                }
                if (f.isDirectory()) {
                    String dirName = f.getName();
                    List<String> fileNames = getFileNames(f.getPath());
                    List<String> dirFileNames = fileNames.stream()
                            .map(n -> dirName + "/" + n).collect(Collectors.toList());
                    list.addAll(dirFileNames);
                }
            });
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
        }
        return list;
    }

}
